<template>
    <div>
        <div class="login-modal">
            <div class="mask" @click="chanIsShowLoginModal(false)"></div>
            <div class="login-box">
                <img class="close" src="@/assets/img/close.png" @click="chanIsShowLoginModal(false)" alt="">
                <ul class="title">
                    <li :class="isShowForm==true?'active':''" @click="isShowForm=true">手机号码登录</li>
                    <li class="divider">|</li>
                    <li  :class="isShowForm==false?'active':''" @click="weixinClick">微信扫码登录</li>
                </ul>
                <div class="body">
                    <div v-show="isShowForm" class="form">
                        <input type="text" class="num_inp" v-model="phoneNumber" placeholder="请输入手机号">
                        <slide-verify :l="42" :r="20" :w="362" :h="140" @success="onSuccess" @fail="onFail" @refresh="onRefresh" 
                        :style="{ width: '100%' }" class="slide-box" ref="slideBlock" :slider-text="msg"></slide-verify>
                        <div class="code">
                            <input type="text" class="code_ipt" placeholder="请输入短信验证码" v-model="SMScode">
                            <div class="get_code login_btn">
                                <span v-show="!isShowCount" @click="getSMScode">获取验证码</span> 
                                <span v-show="isShowCount">{{ count }}s</span>
                            </div>
                        </div>
                        <div class="login_btn" @click="submitLogin">登录</div>
                    </div>
                    <div v-show="!isShowForm" id="weixin" class="qrcode">二维码盒子</div>
                </div>
            </div>
           
        </div>
    </div>
</template>

<script>
import { mapMutations, mapActions } from 'vuex';
import {SendSMSAPI, PhoneReginAPI, WexinBindingApI, UserProfilesAPI} from '@/repuest/api'
import {validatePhoneNumber} from '@/utils'
export default {
    data () {
        return {
            // 是否展示表单
            isShowForm: true,
            // 滑动验证码的提示文本
            msg: "向右滑动",
            // 用户输入的手机号码
            phoneNumber: null,
            // 用户输入的验证码
            SMScode: "",
            // 倒计时的数字
            count: 60,
            // 控制显示和隐藏倒计时数字的变量
            isShowCount: false,
            // timer表示定时器
            timer: null
        }
    },
    methods: {
        ...mapMutations({
            chanIsShowLoginModal: "showLoginModal/chanIsShowLoginModal",
            chanIsLogined: "loginStatus/chanIsLogined"
        }),
        ...mapActions({
            asyncChanIsShowToast: "toastStatus/asyncChanIsShowToast",
            asyncChanUserInfo: "userInfo/asyncChanUserInfo"
        }),
        // 点击切换微信扫码登录这一项，并向微信扫码登录
        weixinClick(){ 
            this.isShowForm=false;

            // 申请微信登录二维码
            let _this = this;
            new WxLogin({
                id: "weixin",
                appid: "wx67cfaf9e3ad31a0d",  // 这个appid要填死
                scope: "snsapi_login",
                // 扫码成功后重定向的接口
                redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
                // state填写编码后的url
                state: encodeURIComponent(window.btoa("http://127.0.0.1:8080" + _this.$route.path)),
                // 调用样式文件
                href: "data:text/css;base64,Lyogd3hsb2dpbi5jc3MgKi8NCi5pbXBvd2VyQm94IC50aXRsZSwgLmltcG93ZXJCb3ggLmluZm97DQogIGRpc3BsYXk6IG5vbmU7DQp9DQoNCi8qIC5pbXBvd2VyQm94IC5xcmNvZGV7DQogIG1hcmdpbi10b3A6IDIwcHg7DQp9ICov",
            });

        },
         // 拼图成功
        onSuccess(times) {
        let ms = (times / 1000).toFixed(1);
        this.msg = "login success, 耗时 " + ms + "s";
        },
        // 拼图失败
        onFail() {
        this.onRefresh(); // 重新刷新拼图
        },
        // 拼图刷新
        onRefresh() {
        this.msg = "再试一次";
        },
        verifyFn() {
            // 1.手机号码的验证
            // if(!正则对象.test(用户输入的信息)){}
            if(!validatePhoneNumber(this.phoneNumber)) {
                asyncChanIsShowToast({
                    msg: "请输入正确的手机号",
                    type: "warn"
                });
                return false;
            }
            // 2.拼图滑块的验证
            if(this.msg == "再试一次" || this.msg == "向右滑动") {
                
                this.asyncChanIsShowToast({
                    msg: "请移动滑块至正确位置",
                    type: "warn"
                });
                return false;
            }
            return true
        },
        async submitLogin() {
            // 点击登录按钮执行这里的代码
            // 1.手机号码的验证
            // 2.拼图滑块的验证
            if(!this.verifyFn()) return;

            // 3.手机验证码的验证
            if(!this.SMScode) {
                this.asyncChanIsShowToast({
                    msg: "请输入验证码",
                    type: "warn"
                });
                return;
            }
            let uuid = localStorage.getItem("uuid");
            let res = null;
            if(uuid) {
                res = await WexinBindingApI({
                    verifyCode: this.SMScode.trim(),
                    phone: this.phoneNumber.trim(),
                    uuid
                })
            }else {
                // 做手机号登录功能
                res = await PhoneReginAPI({
                    verifyCode: this.SMScode.trim(),
                    phone: this.phoneNumber.trim()
                })
            }
            

            // 登录成功之后的逻辑：
            // 1.提示登录成功
            this.asyncChanIsShowToast({
                    msg: "登录成功",
                    type: "success"
            });
            // 2.关闭登录窗口
            this.chanIsShowLoginModal(false);
            // 3.保存token值
            localStorage.setItem("x-auth-token",res["x-auth-token"])
            // 4.登录状态的切换
            this.chanIsLogined(true);
            // console.log(res);
            // 登录成功之后，删除uuid和地址栏上的code
            if(uuid) {
                localStorage.removeItem("uuid");
                this.$router.push(this.$route.path);
            }

            // 登录成功，发起获取用户信息请求
            this.asyncChanUserInfo();
        },
        countDown() {
            // 倒计时的方法
            this.timer = setInterval(() => {
                this.count--;
                if(this.count == 0) {
                    clearInterval(this.timer);
                    this.count = 60;
                    this.isShowCount = false;
                }
            }, 1000); 
        },
       
        async getSMScode() {
            // 点击获取验证码按钮，执行这里的代码

            // 验证手机号码和拼图滑块
            if(!this.verifyFn()) return;

            let res = await SendSMSAPI({
                phone: this.phoneNumber
            })
            console.log(res);
            /* if(res.code == 0) {
                this.isShowCount = true;
                this.countDown();
            } else {
                alert(res.message);
            } */

            if(!res) return;
            this.isShowCount = true;
            this.countDown();
            // 验证通过就可以获取验证码--向后端发起请求,发送成功要变成倒计时
            
        }
    }
}
</script>
 
<style lang = "less" scoped>
@import url(../assets/css/public.less);
    .login-modal {
        width: 100%;
        height: 100%;
        position: fixed;
        left: 0;
        top: 0;
        .mask {
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, .5);
        }
        .login-box {
            width: 555px;
            height: 423px;
            background: url(@/assets/img/login-box-bg.png);

            // 垂直对齐写法 有宽度可以设置
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            right: 0;
            margin: auto;
            .close {
                position: absolute;
                right: 60px;
                top: 10px;
                cursor: pointer;
            }
            .title {
                display: flex;
                justify-content: center;
                padding-top: 40px;
                font-size: 18px;
                color: #ccc;
                li {
                    cursor: pointer;
                }
                .active {
                    color: #333;
                }
                .divider {
                    cursor: auto;
                    margin: -2px 10px 0;
                }
            }
            .body {
                width: 360px;
                margin: 25px auto 0;
                .login_btn {
                    height: 50px;
                    line-height: 50px;
                    text-align: center;
                    font-size: 18px;
                    background-color: @base-color;
                    color: #fff;
                    cursor: pointer;
                }
                .num_inp {
                    border: 1px solid #e4e7eb;
                    text-indent: 10px;
                    height: 50px;
                    margin-bottom: 20px;
                    width: 100%;
                }
                .code {
                    display: flex;
                    justify-content: space-between;
                    height: 50px;
                    margin-bottom: 20px;
                    
                    .code_ipt {
                        flex: 1;
                        border: 1px solid #e4e7eb;
                        text-indent: 10px;
                    }
                    .get_code {
                        width: 100px;
                        margin-left: 10px;
                        font-size: 16px;
                    }
                }

                /*在一些插件和框架中，没有办法直接修改到插件里面的样式，通过/deep/可以直接修改到*/
                /deep/.slide-box {
                    width: 100%;
                    position: relative;
                    box-sizing: border-box;
                    .slide-verify-slider[data-v-7b054e17] {
                        margin-top: 0;
                        margin-bottom: 20px;
                    }
                    canvas {
                        position: absolute;
                        left: 0;
                        top: -120px;
                        display: none;
                        width: 100%;
                        box-sizing: border-box;
                    }
                    .slide-verify-block{
                        width: 85px;
                        height: 136px;
                    }
                    .slide-verify-refresh-icon {
                        top: -120px;
                        display: none;
                    }
                    &:hover {
                        canvas {
                            display: block;
                        }
                        .slide-verify-refresh-icon {
                            display: block;
                        }
                    }
                }
            }
        }
    }
    #weixin {
        display: flex;
        justify-content: center;
    }
</style>